
import store from "@/tools/factory"
import wx from '@/tools/wx'
import {
    getWalletV3,
    getWallet,
    getVehicle
} from '@/api/liubike';
import {
    config,
    defaultAreaId
} from '@/api/config';


/**
 * [getLocation 获取当前地理位置]
 * @return Promise
 */
export const getLocation = type => {
    type = type || 'gcj02';
    return new Promise((resolve, reject) => wx.getLocation({
        type: type,
        complete: resolve,
        fail: reject
    }))
}

/**
 * [throttle 函数节流,防止重复点击]
 * @return Promise
 */
export const throttle = (fn, gapTime) => {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }
    let _lastTime = null
    // 返回新的函数
    return function () {
        let _nowTime = + new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments)   //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}

/**
 * [getUrlKey 解析URL]
 * @return request
 */
export const getQueryArgs = (url) => {
    let theRequest = new Object();
    let strs = url.split("&");
    for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}

/**
 * [checkDeposit 检查押金状态]
 */
export const checkDeposit = (fn) => {
    let depositStatus = store.get("depositInfo").depositStatus;
    let haveCard = store.get("depositInfo").hasDepositCard;
    let hasCreditFree = store.get("depositInfo").hasCreditFree;
    let hasDepositBenefit = store.get("depositInfo").hasDepositBenefit;
    if (!haveCard && !hasCreditFree && !hasDepositBenefit) {
        if (depositStatus == "UNPAID" || depositStatus == "EXPIRE") {
            wx.navigateTo({
                url: `../rechargeDeposit/rechargeDeposit?id=${store.get("loginInfo").id}`
            });
            return false
        }
    }
    if (!store.get("isAuth")) { //未实名认证
        wx.showModal({
            title: "温馨提示",
            content: "实名未认证，请先进行实名认证",
            success(res) {
                if (res.confirm) {
                    wx.navigateTo({
                        url: `../authentication/authentication?id=${store.get("loginInfo").id}`
                    });
                }
            }
        });
        return false;
    }
    fn && fn()
}

//跳过验证
export const skipDeposit = idNum => {
    store.set("firstFlag", "isFlag");
    //存储实名认证成功状态
    if (idNum) {
        store.set('isAuth', 'auth');
        wx.navigateBack({
            delta: 1
        })
    } else {
        getWalletV3({ areaid: store.get("childRouter").areaId || defaultAreaId }).then(res => {
            //免押权益判断
            const data = res.data;
            if (!data.hasDepositCard && !data.hasCreditFree && !data.hasDepositBenefit) {
                if (data.depositStatus == "UNPAID" || data.depositStatus == "EXPIRE") {
                    wx.redirectTo({
                        url: `../rechargeDeposit/rechargeDeposit?id=${store.get("loginInfo").id}`
                    });
                } else {
                    wx.navigateBack({
                        delta: 1
                    })
                }
            } else {
                wx.navigateBack({
                    delta: 1
                })
            }
        })
    }
}

//登录成功后操作
export const loginSuccessHandle = (res, idNumFn) => {
    wx.hideLoading()
    // console.log(res, 'ressssss')
    let req = res.data;
    if (!req.success) {
        if (req.errData && req.errData.errCode == "E2050024") {
            store.set("unionOpenId", req.extra)
            wx.navigateTo({
                url: "/autoLogin"
            })
            return false
        }
        if (req.errData && req.errData.errCode == "E2050013") {
            wx.showModal({
                title: "温馨提示",
                content: req.msg,
                showCancel: false,
                confirmText: "确定",
                success(res) {
                    wx.navigateTo({
                        url: "/mobileLogin"
                    })
                }
            })
            return false
        }
        if (req.errData && req.errData.errCode == "2050009") {
            wx.showModal({
                title: "温馨提示",
                content: req.msg,
                showCancel: false,
                confirmText: "更换号码"
            })
            return false
        }
        wx.showModal({
            title: "温馨提示",
            content: req.msg,
            showCancel: false,
        })
        return false
    };
    store.set('gwsSalt', res.headers.s)
    // 存储登录状态到storageSync
    store.set('loginInfo', {
        id: req.data.id,               // 用户id
        identity: req.data.identity,   // 用户身份证信息
        token: req.data.token,         // 用户登录token
        mileage: req.data.mileage,
        nickName: req.data.nickName,
        integral: req.data.integral,
        phone: req.data.phone,
    });
    //重新初始化banner状态
    store.set("bannerStatus", "open");
    idNumFn && idNumFn(req)
}

//跳过验证
export const skipDeposit_index = (idNum, that) => {
    store.set("firstFlag", "isFlag");
    //存储实名认证成功状态
    if (idNum) {
        store.set('isAuth', 'auth');
        that.initData();
    } else {
        getWalletV3({ areaid: store.get("childRouter").areaId || defaultAreaId }).then(res => {
            //免押权益判断
            const data = res.data;
            // let haveCard = data.hasDepositCard
            if (!data.hasDepositCard && !data.hasCreditFree && !data.hasDepositBenefit) {
                if (data.depositStatus == "UNPAID" || data.depositStatus == "EXPIRE") {
                    wx.navigateTo({
                        url: `../rechargeDeposit/rechargeDeposit?id=${store.get("loginInfo").id}`
                    });
                } else {
                    that.initData();
                }
            } else {
                that.initData();
            }
            // if (data.depositStatus == "CREDIT_FREE") {
            //     // store.set('isAuth', 'auth');
            //     that.initData();
            // } else {
            //     let haveCard = data.hasDepositCard
            //     if (!haveCard && !data.hasCreditFree) {
            //         if (data.depositStatus == "UNPAID" || data.depositStatus == "EXPIRE") {
            //             wx.navigateTo({
            //                 url: `../rechargeDeposit/rechargeDeposit?id=${store.get("loginInfo").id}`
            //             });
            //         } else {
            //             that.initData();
            //         }
            //     } else {
            //         that.initData();
            //     }
            // }
        })
    }
}

//清除所有缓存
export const clearStorge = (type) => {
    if (type == "bike") {
        removeStorages(['orderno', 'returnSuccess', 'rideInfo', "bno", "arrearsState", "unlockPage", "customNo", "progressConfig", "t1"])
    }
    if (type == "user") {
        // gwsign  zkl
        removeStorages(['orderno', 'returnSuccess', 'rideInfo', "bno", "arrearsState", "unlockPage", "customNo", "progressConfig", "t1", "loginInfo", 'gwsSalt'])
    }
}

// 0：正常骑行，1：欠费警告中，2：已断电即将结单，3：临时锁车即将结单，4：临时锁车受限，-1：无欠费保护限制
export const arrearsWarning = (info, that) => {
    if (info.arrearsState) {
        store.set("arrearsState", info.arrearsState);
    } else {
        store.set("arrearsState", "0");
    }
    store.set("power", info.power);
    if (info.vehicleType == 1) {
        if (!info.power && (!info.arrearsState || info.arrearsState != 2)) {
            that.retryPower();
            return false
        }
        if (info.arrearsState == 2) {
            if (info.powerOffRemainingEndTime) {
                let mss = info.powerOffRemainingEndTime;
                let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
                let seconds = (mss % (1000 * 60)) / 1000;
                let time = "";
                if (minutes > 0) {
                    time = `${minutes}分钟`
                } else {
                    time = `${parseInt(seconds)}秒`
                }
                that.setData({
                    errorPowerOff: true,
                    errorPowerOnFail: false,
                    errorTitle: "车辆已断电",
                    errorContent: `将于${time}后自动还车，请尽快充值；或将车辆停放在还车点，摆放整齐后还车`,
                    showErrorDialog: true,
                })
            }
        }
    }
}

//验证是否有试骑次数
export const testRun = (that, fn) => {
    console.log("testRun")
    getWalletV3({ areaid: store.get("childRouter").areaId || defaultAreaId }).then(res => {
        //免押权益判断
        const data = res.data;
        store.set("pushCut", data.pushCut + "");
        //免押状态
        if (data.pushCut) {
            if (store.get("cityRegion")) {
                that.setData({
                    cutLastStep: true,
                    forbidClick: true
                })
            } else {
                that.setData({
                    pushCutView: true
                })
            }
        } else {
            that.setData({
                pushCutView: false,
                cutLastStep: false,
                forbidClick: false
            })
        }
        let depositInfo = {
            depositCardEligible: data.depositCardEligible,
            hasDepositCard: data.hasDepositCard,
            hasCreditFree: data.hasCreditFree,
            hasDepositBenefit: data.hasDepositBenefit,
            depositCardRemains: data.depositCardRemains || 0,
            depositStatus: data.depositStatus || ""
        }
        store.set("depositInfo", depositInfo);

        if (data.depositStatus == "CREDIT_FREE") {
            store.set('isAuth', 'auth');
        }

        if (data.depositStatus == "FREE" && store.get("firstFlag") == "isFlag") {
            that.setData({
                freeOfcharge: true
            })
        } else {
            that.setData({
                freeOfcharge: false
            })
        }
        if (data.hasDepositCard) {
            that.setData({
                showCard: false
            })
        } else {
            if (data.depositCardEligible) {
                store.set("depositNum", data.depositCardRemains)
                that.setData({
                    showCard: true
                })
            } else {
                that.setData({
                    showCard: false
                })
            }
        }
        fn && fn();
    })
}

/**
 * [removeStorages 批量移除本地存储]
 * @param {Array} 删除本地存储key
 */
export const removeStorages = arr => {
    arr.forEach((item) => {
        wx.removeStorageSync(item)
    });
}

/**
 * [setStorages 批量设置本地存储]
 * @param {Object} options
 */
export const setStorages = options => {
    if (isEmpty(options)) return;
    for (let key in options) {
        wx.setStorageSync(key, options[key]);
    }
}

/**
 * [queryVehicleInfo 查询车辆信息]
 * @param {Object} query 查询参数
 * @param {Function} fn 回调函数
 */
export const queryVehicleInfo = (query, fn, errFn) => {
    getVehicle(query).then(res => {
        fn && typeof fn === "function" && fn(res);
    }).catch(err => {
        errFn && typeof errFn === "function" && errFn(err);
    });
}

/**
 * [preventMultipleClickEvent 阻止连续多次点击事件]
 * @param  {Date} t1 [第一次点击的时间]
 * @param  {Date} t2 [第二次点击的时间]
 * @param  {Function} fn [回调函数]
 * @return {null} [无返回值]
 */
let t1 = null;
export const preventMultipleClickEvent = fn => {
    if (t1 == null) {
        t1 = new Date().getTime();
    } else {
        let t2 = new Date().getTime();
        if (t2 - t1 < 5) {
            t1 = t2;
            return;
        } else {
            t1 = t2;
        }
    }
    // 存在回调函数则执行该回调函数
    fn && fn();
}

/**
 * [GetDate 获取指定日期]
 * @param  {Int} AddDayCount 指定日期
 * @return {String} 指定的年月日
 */
export const GetDate = AddDayCount => {
    let dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); // 获取AddDayCount天后的日期
    let y = dd.getFullYear();
    let m = dd.getMonth() + 1; // 获取当前月份的日期
    let d = dd.getDate();
    return y + "-" + m + "-" + d;
}

/**
 * [zeroPadding 时间小于10数字前自动添加0]
 * @param  {String, Int} value [必填]
 * @return {String}   [已添加过0的字符串]
 * @example
 * zeroPadding(2)
 * output: "02"
 */
export const zeroPadding = value => {
    if (value < 0) {
        return false
    }
    return value < 10 ? `0${value}` : `${value}`;
}

/**
 * [isArray 是否为数组]
 * @param  {Array} arr [必填]
 * @return {Boolean} [布尔值]
 * @example
 * const arr = [1,2,3];
 * isArray(arr);
 * output: true
 */
export const isArray = arr => {
    return Array.isArray(arr);
}

/**
 * [getRoute 获取当前页面路径]
 * @return {String}  [当前页面路径]
 * @example
 * getRoute();
 *  output: "pages/index/index"
 */
export const getRoute = () => {
    let currentPageInfo = getCurrentPages();
    if (currentPageInfo[0]) {
        return currentPageInfo[0].route;
    }
}

/**
 * [getParamByName 根据根据参数名在url中获取参数值]
 * @param  {String} name [必填]
 * @param  {String} url  [必填]
 * @return {String} [参数对应的value值]
 * @example:
 * getParamByName('name', 'pages/index/index?name=xiaxs');
 *  output: "xiaxs"
 */
export const getParamByName = (name, url) => {
    url = url || getRoute() || window.location;
    let match = RegExp('[?&]' + name + '=([^&]*)').exec(url);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '))
}

/**
 * [isEmpty 判断json对象是否为空]
 * @param  {Object} target [必填]
 * @return {Boolean} true | false
 */
export const isEmpty = target => {
    if (!target) {
        return true;
    } else if (typeof target === 'object' && !Object.keys(target).length) {
        return true;
    } else {
        return false;
    }
}

/**
 * [getDistance 获取经纬度之间的直线距离]
 * @param  {Object} from [起始经纬度,必填]
 * @param  {Object} to [结束经纬度,必填]
 * @return {Int} s [距离值]
 */
const Rad = d => {
    return d * Math.PI / 180.0; // 经纬度转换成三角函数中度分表形式
}
export const getDistance = (from, to) => {
    let radLat1 = Rad(from.lat1);
    let radLat2 = Rad(to.lat);
    let a = radLat1 - radLat2;
    let b = Rad(from.lng1) - Rad(to.lng);
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; // 输出为公里
    return s;
}

/**
 * [rayCasting 射线法判断点是否在多边形内部]
 * @param  {Object} p 待判断的点, 格式: { x: X坐标, y: Y坐标 }
 * @param  {Array}  poly 多边形顶点, 格式: { x: X坐标, y: Y坐标 }
 * @return {String} 点 p 和多边形 poly 的几何关系
 */
export const rayCasting = (p, poly) => {
    let px = p.x,
        py = p.y,
        flag = false

    for (let i = 0, l = poly.length, j = l - 1; i < l; j = i, i++) {
        let sx = poly[i].x,
            sy = poly[i].y,
            tx = poly[j].x,
            ty = poly[j].y

        // 点与多边形顶点重合
        if ((sx === px && sy === py) || (tx === px && ty === py)) {
            return 'on'
        }

        // 判断线段两端点是否在射线两侧
        if ((sy < py && ty >= py) || (sy >= py && ty < py)) {
            // 线段上与射线 Y 坐标相同的点的 X 坐标
            let x = sx + (py - sy) * (tx - sx) / (ty - sy)

            // 点在多边形的边上
            if (x === px) {
                return 'on'
            }

            // 射线穿过多边形的边界
            if (x > px) {
                flag = !flag
            }
        }
    }

    // 射线穿过多边形边界的次数为奇数时点在多边形内
    return flag ? 'in' : 'out';
}

/**
 * 数据美化，js对于浮点类型数据计算不精确，会出现小数点后n位的情况
 * @param {*} numb
 */
export const beautyNumber = (numb) => {
    var n = parseFloat(numb);
    if (isNaN(n)) {
        return numb;
    }
    // n = Math.round(n * 100) / 100;
    n = Math.ceil(n * 100) / 100;
    if (n > 10000) {
        return n + "";
    }
    var ns = n.toString();
    if (ns.indexOf(".") < 0) {
        return n + ".00";
    }

    if (ns.substring(ns.indexOf(".") + 1, ns.length).length < 2) {
        return n + "0";
    }
    return n + "";
}

/**
 * 获取两经纬度之前的倾斜角度
 * @param {*} numb
 */
export const getAngle = (lng_a, lat_a, lng_b, lat_b) => {
    var a = (90 - lat_b) * Math.PI / 180;
    var b = (90 - lat_a) * Math.PI / 180;
    var AOC_BOC = (lng_b - lng_a) * Math.PI / 180;
    var cosc = Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math.cos(AOC_BOC);
    var sinc = Math.sqrt(1 - cosc * cosc);
    var sinA = Math.sin(a) * Math.sin(AOC_BOC) / sinc;
    var A = Math.asin(sinA) * 180 / Math.PI;
    var res = 0;
    if (lng_b > lng_a && lat_b > lat_a) res = A;
    else if (lng_b > lng_a && lat_b < lat_a) res = 180 - A;
    else if (lng_b < lng_a && lat_b < lat_a) res = 180 - A;
    else if (lng_b < lng_a && lat_b > lat_a) res = 360 + A;
    else if (lng_b > lng_a && lat_b == lat_a) res = 90;
    else if (lng_b < lng_a && lat_b == lat_a) res = 270;
    else if (lng_b == lng_a && lat_b > lat_a) res = 0;
    else if (lng_b == lng_a && lat_b < lat_a) res = 180;
    return res;
}

